import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/log_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/model/event/file_event.dart';
import 'package:leader_doctor_flutter/plugins/plugins_messages.g.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:netease_meeting_ui/meeting_ui.dart';

/// @Author lixiaobin
/// @Date 2023/12/11
/// @Description 意见反馈
class FeedBackPage extends StatefulWidget {
  const FeedBackPage({super.key});

  @override
  State<FeedBackPage> createState() => _FeedBackPageState();
}

class _FeedBackPageState extends State<FeedBackPage> {
  final _textEditingController = TextEditingController();
  final _imgList = <String>[
    // 'https://service.echartnow.com/ecology/0_test/guardUploadFile/1232011/1737357397180055552_f657c505f51646faa9822b2b3e06cbe4.jpg',
    // 'https://service.echartnow.com/ecology/0_test/guardUploadFile/1232011/1737357397180055552_f657c505f51646faa9822b2b3e06cbe4.jpg',
    'add'
  ];

  @override
  void initState() {
    super.initState();
    App.instance.eventBus.on<FileEvent>().listen((event) {
      _upFile(event.fileList);
    });

    _textEditingController.addListener(() {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: CommWidget.getCommAppbar(context),
        body: GestureDetector(
            onTap: () {
              FocusScopeNode currentFocus = FocusScope.of(context);
              if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
                FocusManager.instance.primaryFocus?.unfocus();
              }
            },
            child: Container(
                height: double.infinity,
                color: ColorRes.white,
                child: Column(
                  children: [
                    Container(
                        padding: EdgeInsets.only(left: 12.w, right: 12.w),
                        child: Column(
                          children: [
                            SizedBox(
                                height: 50.w,
                                child: Row(
                                  children: [
                                    ImageLoader.loadAsset('must_input.png', 7.w),
                                    Text(
                                      '问题详情描述',
                                      style: TextStyle(
                                          fontWeight: FontWeight.w500, color: ColorRes.color333333, fontSize: 16.sp),
                                    )
                                  ],
                                )),
                            Container(
                              height: 200.w,
                              width: double.infinity,
                              padding: EdgeInsets.all(12.w),
                              decoration:
                                  BoxDecoration(color: ColorRes.colorF9F9FA, borderRadius: BorderRadius.circular(4.w)),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Expanded(
                                      child: TextField(
                                    controller: _textEditingController,
                                    maxLength: 200,
                                    maxLines: 20,
                                    style: TextStyle(fontSize: 14.sp),
                                    decoration: InputDecoration(
                                        contentPadding: EdgeInsets.zero,
                                        isDense: true,
                                        counterText: '',
                                        hintText: '请输入您的详细问题，我们将尽快为您解决。',
                                        hintStyle: TextStyle(color: ColorRes.colorb7b7b7, fontSize: 14.sp),
                                        border: InputBorder.none),
                                  )),
                                  Text(
                                    '${_textEditingController.text.length}/200',
                                    style: TextStyle(color: ColorRes.colorb7b7b7, fontSize: 14.sp),
                                  )
                                ],
                              ),
                            ),
                            SizedBox(height: 20.w),
                            Row(
                              children: [
                                Text(
                                  '上传图片',
                                  style: TextStyle(
                                      fontWeight: FontWeight.w500, color: ColorRes.color333333, fontSize: 16.sp),
                                ),
                                Text(
                                  '（${_imgList.contains('add') ? (_imgList.length - 1) : _imgList.length}/5）',
                                  style: TextStyle(color: ColorRes.color999999, fontSize: 13.sp),
                                )
                              ],
                            ),
                            SizedBox(height: 10.w),
                          ],
                        )),
                    // Container(
                    //     height: 75.w,
                    //     width: double.infinity,
                    //     padding: EdgeInsets.only(left: 2.w, right: 12.w),
                    //     child: Row(
                    //       children: _itemList(),
                    //     )),
                    Container(
                        margin: EdgeInsets.only(left: 16.w, right: 10.w),
                        width: double.infinity,
                        child: GridView.builder(
                            itemCount: _imgList.length,
                            shrinkWrap: true,
                            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 3,
                                crossAxisSpacing: 13.w,
                                mainAxisSpacing: 13.w,
                                childAspectRatio: 1.0),
                            itemBuilder: _itemBuilder)),
                    SizedBox(height: 52.w),
                    Container(
                        padding: EdgeInsets.only(left: 12.w, right: 12.w),
                        child: CommWidget.buildRightBtn('确定保存', () => _commit(context)))
                  ],
                ))));
  }

  List<Widget> _itemList() {
    var viewArr = <Widget>[];
    for (int i = 0; i < 5; i++) {
      Container container;
      if (i < _imgList.length) {
        var imageUrl = _imgList[i];
        container = Container(
          padding: EdgeInsets.only(left: 10.w),
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(4.w)),
          child: imageUrl == 'add' ? _getAddImage() : _getImage(imageUrl),
        );
      } else {
        container = Container(
          margin: EdgeInsets.only(left: 10.w),
        );
      }
      viewArr.add(Expanded(child: container));
    }
    return viewArr;
  }

  Widget _itemBuilder(BuildContext context, int index) {
    var imageUrl = _imgList[index];
    return Container(
      decoration: BoxDecoration(borderRadius: BorderRadius.circular(4.w)),
      child: imageUrl == 'add' ? _getAddImage() : _getImage(imageUrl),
    );
  }

  Widget _getAddImage() {
    return GestureDetector(
        onTap: () {
          NativeInterface().selectFile(1, 'image');
        },
        child: Container(
          width: double.infinity,
          height: double.infinity,
          margin: EdgeInsets.only(top: 7.w, right: 7.w),
          decoration: BoxDecoration(borderRadius: BorderRadius.circular(4.w), color: ColorRes.colorF9F9FA),
          child: Stack(alignment: Alignment.center, children: [
            ImageLoader.loadAsset('icon_feed_back_add.webp', 24.w),
          ]),
        ));
  }

  Widget _getImage(String url) {
    return Container(
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(4.w)),
        width: double.infinity,
        height: double.infinity,
        child: Stack(
          alignment: Alignment.topRight,
          children: [
            Positioned.fill(
              top: 7.w,
              right: 7.w,
              child: ClipRRect(
                  borderRadius: BorderRadius.circular(4.w), child: ImageLoader.loadImage(url, fit: BoxFit.fill)),
            ),
            GestureDetector(
                onTap: () {
                  listChange(false, url);
                  setState(() {});
                },
                child: ImageLoader.loadAsset('icon_close.webp', 14.w)),
          ],
        ));
  }

  _upFile(List<FileInfo?> fileList) async {
    var httpRequest = HttpRequest(Api.fileUpload, files: fileList);
    var httpResponse = await HttpClient.postFileBytes(httpRequest);
    if (httpResponse.success) {
      var serviceResult = ServiceResult<String?>.simple(httpResponse);
      var url = serviceResult.responseBody;
      listChange(true, url!);
    }
  }

  listChange(bool isAdd, String url) {
    Log.d(url);
    _imgList.remove('add');
    isAdd ? _imgList.add(url) : _imgList.remove(url);
    if (_imgList.length < 5) {
      _imgList.add('add');
    }
    setState(() {});
  }

  _commit(BuildContext context) async {
    var text = _textEditingController.text;
    if (text.isEmpty) {
      ToastUtils.showToast(context, '请输入问题描述');
      return;
    }
    var imageStr = '';
    _imgList.where((e) => e != 'add').forEach((e) => imageStr += e);
    var httpRequest = HttpRequest(Api.feedback, body: {
      "userId": App.instance.userInfo?.id,
      "userType": '1',
      'feedback': text,
      'feedbackImgs': imageStr,
    });
    await HttpClient.postJson(httpRequest);
    ToastUtils.showToast(context, '提交成功');
    context.pop();
  }
}
